/**
* File Name: server.c
* Auther: Jichang
* Environment: Fedora 7 server
* server
*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<ctype.h>

#define SERV_PORT 9527

void sys_err(const char *str)
{
	perror(str);
	exit(1);
}

int main(int argc, char *argv[])
{
	int lfd = 0, cfd;
	int ret = 0;
	struct sockaddr_in serv_addr, client_addr;
	socklen_t client_addr_len;
	char buf[BUFSIZ], client_IP[1024]; // BUFSIZ is 4096

	// init.
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(SERV_PORT);
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	// create socket.
	lfd = socket(AF_INET, SOCK_STREAM, 0);
	if(lfd == -1) {
		sys_err("socket error");
	}
	// bind
	ret = bind(lfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
	if(ret != 0) {
		sys_err("bind error");
	}

	// listen
	ret = listen(lfd, 128);
	if(ret != 0) {
		sys_err("listen error");
	}
	
	// accept
	cfd = accept(lfd, (struct sockaddr *)&client_addr, &client_addr_len);
	if(cfd == -1) {
		sys_err("accept error");
	}
	printf("client ip: %s, port: %d\n", 
			inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, client_IP, sizeof(client_IP)),
			ntohs(client_addr.sin_port));

	// read something
	while(1) {
		ret = read(cfd, buf, sizeof(buf));
		if(ret == -1) {
			sys_err("read error");
		}
		write(STDOUT_FILENO, buf, ret);
		// Upper
		for(int i = 0; i < ret; i++) {
			buf[i] = toupper(buf[i]); // upper
		}
		// write
		write(cfd, buf, ret);		
	}
	close(lfd);
	close(cfd);


	return 0;
}

